import { defineStore } from "pinia";
import {userApi} from '@/api/user.ts'
import {getToken,setToken,removeToken} from '@/utils/token-utils.ts'
import router from '@/router'
import { allAsyncRoutes,staticRoutes,anyRouter} from "@/router/routes";
import type { RouteRecordRaw } from "vue-router";
import cloneDeep from 'lodash/cloneDeep'
/* function filterUserRoutes(allAsyncRoutes: RouteRecordRaw[], userRoutes: string[]): RouteRecordRaw[] {
    return allAsyncRoutes.filter(item => {
      const match = userRoutes.find((userItem: any) => userItem == item.name);
      if (match) {
        if (item.children && item.children.length) {
          item.children = filterUserRoutes(item.children, userRoutes);
        }
        return true;
      }
      return false;
    });
  } */

function addUserAsyncRoutes(userAsyncRoutesAndAnyRoute:RouteRecordRaw[]){
    userAsyncRoutesAndAnyRoute.forEach(item=>{
      router.addRoute(item)
    })
  }
  
function clearRoutes(){
    let routes = router.getRoutes()
    routes.forEach(item=>{
      router.removeRoute(item.name as string)
    })
    // 增加静态路由
    addUserAsyncRoutes(staticRoutes)
  }

function filterUserRoutes(allAsyncRoutes: RouteRecordRaw[], userRole:string){
  let userRoutes:RouteRecordRaw[] = []
  if(userRole === "user"){
    userRoutes = allAsyncRoutes.filter(item=>item.name!=="RootDeviceManage")
  }else{
    userRoutes = allAsyncRoutes
  }
  return userRoutes
}


interface UserData{
  token:string | null,
  menus: RouteRecordRaw[],
  userInfo:{
    username:string
  },
  [key: string]: any
}

const getUserData = ():UserData=>{
  return {
    token:getToken(),
    menus:[],
    userInfo:{
      username:""
    }
  }
}

export const useUserInfoStore = defineStore("userInfo", {
    state:()=>{
        return getUserData()
    },
    actions:{
        async login(loginParams:any){
            try {
              const res = await userApi.login(loginParams)
              const{ token} = res.data
                setToken(token)
                this.token = token
                return "ok";
            } catch (error) {
                return Promise.reject("fail");
            }
        },
        async getUserInfo(){
          try {
          const res:any =await userApi.reqGetUserInfo()
          const {username,userrole} = res.data
          this.userInfo.username = username
          let useAsyncRoutes = filterUserRoutes(cloneDeep(allAsyncRoutes),userrole)
          addUserAsyncRoutes(useAsyncRoutes.concat(staticRoutes,anyRouter))
          this.menus = staticRoutes.concat(useAsyncRoutes,anyRouter)
          return "ok";
          } catch (error) {
          return Promise.reject(error);      
          }
        },
        reset(){
          removeToken()  
          const defaultData:UserData = getUserData();
          Object.keys(defaultData).forEach((key) => {
            this[key] = defaultData[key];
          });  
        },

        async loginOut(){
          try {
          await userApi.loginOut()   
          this.reset();
          clearRoutes()
          } catch (error) {    
          return Promise.reject("fail");           
          }
      }

      },
})